package com.todod.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.todod.common.util.HtmlToWord;
import com.todod.common.util.TododDate;
import com.todod.dto.ShuoMingFileDto;
import com.todod.entity.QueryProjectInfo;
import com.todod.entity.ResultData;
import com.todod.mapper.ShuoMingFileMapper;
import com.todod.model.MdTemplate;
import com.todod.model.ShuoMingFile;
import com.todod.model.User;
import com.todod.service.IMdTemplateService;
import com.todod.service.IUserService;
import com.todod.service.ShuoMingFileService;

@RestController
@RequestMapping("/shuoMingFile")
public class ShuoMingFileController {
	@Autowired
	private ShuoMingFileService shuoMingFileService;
	@Autowired
	private ShuoMingFileMapper shuoMingFileMapper;
	@Autowired
	private IUserService iUserService;
	@Value("${file.upload.path}")
	private String uploadPath;
	@Value("${file.upload.mapping}")
	private String showPath;
	@Value("${file.visit}")
	private String visi;
	@Value("${file.downloadDir}")
	private String downloadDir;
	@Autowired
	private IMdTemplateService mdTemplateService;

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getListPage")
	public ResultData getListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryProjectInfo queryProjectInfo) {

		IPage<ShuoMingFileDto> page = shuoMingFileService.getListPage(_userId, queryProjectInfo);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param _userId
	 * @param reqShuoMingFile
	 * @return
	 */
	@PostMapping("/save")
	public ResultData save(@RequestAttribute Long _userId, @RequestBody ShuoMingFile shuoMingFile) {
		shuoMingFileService.save(_userId, shuoMingFile);
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param reqShuoMingFile
	 * @return
	 */
	@PostMapping("/edit")
	public ResultData edit(@RequestAttribute Long _userId, @RequestBody ShuoMingFile shuoMingFile) {
		shuoMingFileService.edit(_userId, shuoMingFile);
		return ResultData.success();
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	public ResultData delete(@RequestAttribute Long _userId, Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		ShuoMingFile shuoMingFile = shuoMingFileMapper.selectById(code);
		if (!_userId.equals(shuoMingFile.getCreateuserId())) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "不可删除非当前登录人创建的文档");
		}
		shuoMingFile.setFlag(2);
		shuoMingFile.setModifyuserId(_userId);
		shuoMingFile.setModifytimeTi(LocalDateTime.now());
		shuoMingFileMapper.updateById(shuoMingFile);
		return ResultData.success();
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@PostMapping("/getInfo")
	public ResultData getInfo(String code, String isNew) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		List<ShuoMingFileDto> list = shuoMingFileMapper.getInfo(code, isNew);
		for (ShuoMingFileDto shuoMingFile : list) {
			User user = iUserService.getById(shuoMingFile.getCreateuserId());
			shuoMingFile.setCreateuserName(user.getNickName());
		}

		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@PostMapping("/getHistryList")
	public ResultData getHistryList(String code) {

		List<ShuoMingFileDto> list = shuoMingFileService.getListByCode(code);
		for (ShuoMingFileDto shuoMingFile : list) {
			User user = iUserService.getById(shuoMingFile.getCreateuserId());
			shuoMingFile.setCreateuserName(user.getNickName());
		}

		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getFileList")
	public ResultData getFileList(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);

		List<ShuoMingFileDto> list = shuoMingFileMapper.getFileList(_userId, user.getDepartid());
		return ResultData.success("ok", list);
	}

	/**
	 * 导出word
	 * 
	 * @Title: downloadWord
	 * @Description:
	 * @author gsh
	 * @date 2019年9月24日
	 * @param flag
	 * @param ids
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/downloadWord")
	public ResultData downloadWord(HttpServletRequest request, HttpServletResponse response, String flag, String ids)
			throws IOException {

		if (ids == null || StringUtils.isBlank(ids)) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		List<ShuoMingFile> list = null;
		String[] sp = ids.split(",");
		if ("XM".equals(flag) && sp.length > 0) { // 导出项目下全部
			list = shuoMingFileMapper.getListByXmId(sp[0]);
		} else { // 根据id导出
			list = new ArrayList<ShuoMingFile>();
			for (String id : sp) {
				ShuoMingFile apiListByClassifyId = shuoMingFileMapper.selectById(id);
				list.add(apiListByClassifyId);
			}
		}

		if (list == null || list.size() == 0) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "无数据");
		}
		// 生成 html
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			ShuoMingFile dataDictory = list.get(i);

			sb.append("<h1>" + (i + 1) + ". " + dataDictory.getTableName() + "</h1>" + dataDictory.getHtmlData());
		}

		String newDate = TododDate.getInstance().getSimpledate();

		// 上传路径
		String path = uploadPath + File.separator + "file" + File.separator + newDate;
		String pdfName = UUID.randomUUID().toString() + ".pdf";
		String root = path + File.separator + pdfName;
		String relativePath = downloadDir + showPath + "/file" + "/" + newDate + "/" + pdfName;

		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		OutputStream out = new FileOutputStream(root);

		HtmlToWord.htmlToWord(sb.toString(), out, root);

		return ResultData.success("ok", relativePath);
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@PostMapping("/getMdTemplate")
	public ResultData getMdTemplate(@RequestAttribute Long _userId) {

		User user = iUserService.getById(_userId);

		MdTemplate byDefaultData = mdTemplateService.getByDefaultDataByType("2", user.getDepartid());
		String template = byDefaultData.getMarkdownData();

		return ResultData.success("ok", template);
	}

}
